import numpy as np
import pandas as pd

data = {

    'A': [1, 0, 1, 1, 2, 2, 3, 4],
    'B': [0, 2, 5, 0, 2, 2, 2, 2],
    'C': [4, 0, 4, 4, 3, 3, 3, 3],
    'D': [1, 0, 1, 1, 4, 4, 4, 4]
}

df = pd.DataFrame(data=data, index=pd.date_range('12/1/2020', periods=8))
print(df)
print(df.rolling(window=3).mean())
print(df.expanding(min_periods=3).mean())  # 开始到当前行
print(df.ewm(com=0.5).mean())

r = df.rolling(window=3, min_periods=1)  # 从当前行往前3行求sum
print(r.aggregate(np.sum))
print(r['A'].aggregate(np.sum))
print(r['A', 'B'].aggregate(np.sum))
# print(r['A','B'].aggregate(np.sum,np.mean))

# 重置index
df = df.reindex(index=pd.date_range('12/1/2020', periods=11))
print(df)
print(df['A'].isnull())
print(df.notnull())

# 缺失值处理
print(df.fillna(0))
print(df.fillna(method='ffill'))  # 向前填充
print(df.fillna(method='bfill'))  # 向后填充
print(df.dropna())
